﻿
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Yuebon.WebApi.Common
{
    /// <summary>
    /// 对需要进行授权登录的接口生成对应的文档输入框，如Bearer Token
    /// </summary>
    public class HttpHeaderOperation: IOperationFilter
    {
        /// <summary>
        /// 实现Apply
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {

            var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
            .Union(context.MethodInfo.GetCustomAttributes(true))
            .OfType<AuthorizeAttribute>();

            if (authAttributes.Any())
                operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });

            //if (operation.Parameters == null)
            //{
            //    operation.Parameters = new List<OpenApiParameter>();
            //}
            //if (context.ApiDescription.TryGetMethodInfo(out MethodInfo methodInfo))
            //{
            //    if (!methodInfo.CustomAttributes.Any(t => t.AttributeType == typeof(AllowAnonymousAttribute))
            //            && !(methodInfo.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(AuthorizeAttribute))))
            //    {
            //    }
            //}
        }
    }
}
